<template>
  <div>
    <div style="width:350px;float:left;">
      <el-scrollbar>
          <basic-container class="tab-content-title">
            <div class="gis-main-container">
              <div class="tab-content-title">
                <div class="distinct-title" @click="selectDept('distinct')"><i class="el-icon-map-location" /> {{ distinct }}</div>
                <!-- <el-button @click="showHouseDetailWindow(2)">dd</el-button> -->
              </div>
              <el-tabs v-model="activeName" @tab-click="handleClick" style="clear:both;float:left;width:100%;">
                <el-tab-pane label="基本信息" name="first">
                  <div class="collapse-title" @click="show1 = !show1">
                    <span>网格信息</span>
                    <i :class="show1 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
                  </div>
                  <el-collapse-transition>
                    <div class="grid-info" v-show="show1">
                      <div class="top-list-container">
                          <div class="top-list" @click="initGrid()">
                              <div class="img-bg" title="网格"></div>
                              <div class="count-num">{{c1}}</div>
                          </div>
                          <div class="top-list" @click="initGridWorker()">
                              <div class="img-bg2" title="网格员"></div>
                              <div class="count-num">{{c2}}</div>
                          </div>
                          <div class="top-list" @click="initGridArea()">
                              <div class="img-bg3" title="网格面积"></div>
                              <div class="count-num">{{c3}}</div>
                          </div>
                          <div class="top-list" @click="initGridSpecial()">
                              <div class="img-bg4" title="特殊人员"></div>
                              <div class="count-num">{{c4}}</div>
                          </div>
                      </div>
                    </div>
                  </el-collapse-transition>

                  <div class="collapse-title" @click="show2 = !show2">
                    <span>人口统计</span>
                    <i :class="show2 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
                  </div>
                  <el-collapse-transition>
                    <div id="basePeopleCount" class="people-count" v-show="show2">
                      <div id="pieChart" style="width:100%;height:210px" ref="pieChart"></div>
                    </div>
                  </el-collapse-transition>

                  <div class="collapse-title" @click="show3 = !show3">
                    <span>实有人口查询</span>
                    <i :class="show3 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
                  </div>
                  <el-collapse-transition>
                    <div v-show="show3">
                      <el-form ref="form" :model="form" label-width="80px!important">
                          <el-form-item label="区域范围">
                            <el-input v-model="areaText" readonly="true" v-on:click.native="selectDept('areaText')" size="mini"></el-input>
                            <input id="treeType" name="treeType"  type="hidden" value="grid"/>
                            <input id="treeId" name="treeType" type="hidden" v-model="areaId"/>
                          </el-form-item>
                          <el-form-item label="分类">
                            <el-col :span="11">
                              <el-select placeholder="民族" size="mini" v-model="nationId" clearable>
                                <el-option v-for="(option,index) in nation" :key="index" v-bind:label="option.text" v-bind:value="option.value"></el-option>
                              </el-select>
                            </el-col>
                            <el-col class="collapse-line" :span="2"></el-col>
                            <el-col :span="11">
                              <el-select  placeholder="居民类型" size="mini" v-model="populationTypeId" clearable>
                                <el-option v-for="(option,index) in sys_population_type" :key="index" v-bind:label="option.text" v-bind:value="option.value"></el-option>
                              </el-select>
                            </el-col>
                            <el-col :span="11">
                              <el-select  placeholder="学历" size="mini" v-model="educationCode" clearable>
                                <el-option v-for="(option,index) in education" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                              </el-select>
                            </el-col>
                            <el-col class="collapse-line" :span="2"></el-col>
                            <el-col :span="11">
                              <el-select placeholder="宗教类型" size="mini" v-model="religionId" clearable>
                                <el-option v-for="(option,index) in religion" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                              </el-select>
                            </el-col>
                            <el-col :span="24">
                              <el-select placeholder="政治面貌" style="width:100%;" size="mini" v-model="partyId" clearable>
                                <el-option v-for="(option,index) in party" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                              </el-select>
                            </el-col>
                          </el-form-item>
                          <el-form-item label="姓名">
                            <el-input v-model.lazy.trim="name" size="mini" clearable></el-input>
                          </el-form-item>
                          <el-form-item label="身份证号">
                            <el-input v-model.trim="idCard" size="mini" clearable></el-input>
                          </el-form-item>
                          <el-form-item label="年龄范围">
                            <el-col :span="11">
                              <el-input v-model.trim="ageFrom" size="mini" type="number" @input="changeFrom" clearable></el-input>
                            </el-col>
                            <el-col class="collapse-line" :span="2">-</el-col>
                            <el-col :span="11">
                              <el-input v-model.trim="ageTo" size="mini" type="number" @input="changeTo" clearable></el-input>
                            </el-col>
                          </el-form-item>
                          <el-form-item>
                            <el-button @click="resetForm()" size="mini">重置</el-button>
                            <el-button type="primary" @click="queryButton" size="mini" >搜索</el-button>
                          </el-form-item>
                      </el-form>
                    </div>
                  </el-collapse-transition>

                </el-tab-pane>
                <el-tab-pane label="特殊人群" name="second">
                  <div class="collapse-title" @click="show4 = !show4">
                    <span>人数统计</span>
                    <i :class="show4 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
                  </div>
                  <el-collapse-transition>
                    <div id="focusPeopleCount" class="people-count" style="height: 300px;" v-show="show4">
                      <div id="focusPieChart" style="width:100%;height:300px" ref="focusPieChart"></div>
                    </div>
                  </el-collapse-transition>

                  <div class="collapse-title" @click="show5 = !show5">
                    <span>人员搜索</span>
                    <i :class="show5 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
                  </div>
                  <el-collapse-transition>
                    <div v-show="show5">
                      <el-form ref="form" :model="form" label-width="80px!important">
                        <el-form-item label="区域范围">
                          <el-input v-model="areaText" readonly="true" v-on:click.native="selectDept('areaText')" size="mini"></el-input>
                          <input id="treeType" name="treeType"  type="hidden" value="grid"/>
                          <input id="treeId" name="treeType" type="hidden" v-model="areaId"/>
                        </el-form-item>
                        <el-form-item label="分类">
                          <el-col :span="11">
                            <el-select placeholder="特殊人员类型" size="mini" v-model="focusTypeId" clearable>
                              <el-option v-for="(option,index) in types_of_key_personnel" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>
                          <el-col class="collapse-line" :span="2"></el-col>
                          <el-col :span="11">
                            <el-select  placeholder="民族" size="mini" v-model="nationId" clearable>
                              <el-option v-for="(option,index) in nation" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>

                          <el-col :span="11">
                            <el-select placeholder="居民类型" size="mini" v-model="populationTypeId" clearable>
                              <el-option v-for="(option,index) in sys_population_type" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>
                          <el-col class="collapse-line" :span="2"></el-col>
                          <el-col :span="11">
                            <el-select  placeholder="学历" size="mini" v-model="educationCode" clearable>
                              <el-option v-for="(option,index) in education" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>
                          <el-col :span="11">
                            <el-select placeholder="宗教类型" size="mini" v-model="religionId" clearable>
                              <el-option v-for="(option,index) in religion" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>
                          <el-col class="collapse-line" :span="2"></el-col>
                          <el-col :span="11">
                            <el-select placeholder="政治面貌" size="mini" style="width:100%;" v-model="partyId" clearable>
                              <el-option v-for="(option,index) in party" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                            </el-select>
                          </el-col>
                        </el-form-item>
                        <el-form-item label="姓名">
                          <el-input v-model.lazy.trim="name" size="mini" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="身份证号">
                          <el-input v-model.trim="idCard" size="mini" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="年龄范围">
                          <el-col :span="11">
                            <el-input v-model.trim="ageFrom" size="mini" type="number" @input="changeFrom" clearable></el-input>
                          </el-col>
                          <el-col class="collapse-line" :span="2">-</el-col>
                          <el-col :span="11">
                            <el-input v-model.trim="ageTo" size="mini" type="number" @input="changeTo" clearable></el-input>
                          </el-col>
                        </el-form-item>
                        <el-form-item>
                          <el-button @click="resetForm()" size="mini">重置</el-button>
                          <el-button type="primary" @click="queryButton" size="mini" >搜索</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-collapse-transition>
                </el-tab-pane>
              </el-tabs>
            </div>
          </basic-container>
        </el-scrollbar>
    </div>
    <div style="width:calc(100% - 400px);position: absolute;left:380px;height:calc(100% - 50px)">
        <basic-container>
          <div id="mapDiv" class="map-container">
              <div id="homebutton"></div>
          </div>
        </basic-container>
    </div>

    <!-- 网格员列表 -->
    <el-dialog
      ref="gridDialog"
      append-to-body
      :visible.sync="gridWorkerFlowBox"
      :fullscreen="false"
      custom-class="people_dialog"
      :class="minimizeClass"
      :modal="modalFlag"
    >
      <template slot="title">
        <div>
          <span>网格员列表    -<font id="workerCount">{{ workerTitleText }}</font></span>
          <!-- <div class="minimize-button" @click="miniWindow"><icon class="el-icon-cpu" /></div> -->
          <div class="search-button" @click="closeSearch"><icon class="el-icon-search" /></div>
        </div>
      </template>
      <div class="people-list-window" id="workerListWindow">
        <div class="window">
            <div class="search-panel" id="workerSearchPanel">
                <label>姓名&nbsp;&nbsp;</label><input v-model.trim="workerName"><label>性别&nbsp;&nbsp;</label>
                <select v-model="workerSex"><option value="">请选择</option><option value="1">男</option><option value="2">女</option></select>
                <label>电话&nbsp;&nbsp;</label><input v-model="workerPhone">
                <input type="radio" name="type" value="('01','03')" v-model="workerType">专职
                <input type="radio" name="type" value="('02')" v-model="workerType">兼职
                <input type="radio" name="type" value="('01','02','03')" v-model="workerType">全部
                <button id="search" @click="searchWorker()">搜索</button>
            </div>

            <div class="window-content" id="workerListContent" style="padding-left:0px;padding-right:0px;overflow:hidden;">
                <div class="table-container" style="overflow:hidden;">
                  <el-table
                    :data="tableData"
                    border
                    style="width: 100%;">
                    <el-table-column
                      prop="name"
                      label="姓名"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="sex"
                      label="性别"
                      sortable
                    >
                      <template slot-scope="scope">
                        {{scope.row.sex == "1" ? "男":(scope.row.sex == "2"?"女":'')}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="phoneNum"
                      label="联系电话"
                      width="120">
                    </el-table-column>
                    <el-table-column
                      prop="gridName"
                      label="所属网格"
                      width="160"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="gridArea"
                      label="网格面积㎡"
                      sortable
                      width="120"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="workerType"
                      label="人员类型"
                      sortable
                      width="110"
                    >
                      <template slot-scope="scope">
                        {{workerTypeCode[scope.row.workerType]}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="gridId"
                      label="GIS"
                      width="50">
                      <template slot-scope="scope">
                        <icon class="el-icon-aim" @click="zoomToWorker(scope.row.id)" :style="scope.row.lat ? 'color:blue':''" />
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="workerCount"
                  :page-size="page.pageSize"
                  :current-page.sync="page.currentPage"
                  @current-change="handleCurrentChange"
                  style="text-align: center;">
                </el-pagination>
            </div>
        </div>
      </div>
    </el-dialog>

    <!-- 网格简介 -->
    <el-dialog
      ref="gridDInfoialog"
      append-to-body
      :visible.sync="gridWorkerInfoFlowBox"
      :fullscreen="false"
      custom-class="people_dialog"
      :class="minimizeClass"
      :modal="modalFlag"
    >
      <template slot="title">
        <div>
          <span>{{ gridArea.gridName }}<font>网格简介</font></span>
          <!-- <div class="minimize-button" @click="miniWindow"><icon class="el-icon-cpu" /></div> -->
        </div>
      </template>
      <div class="people-list-window" id="gridInfoWindow">
        <div class="window">
            <div class="window-content">
                <div class="top">
                    <div class="left-text">
                        <textarea readonly v-bind:value="gridArea.gridBrief" style="border:#ccc 1px solid;margin-top:10px;"></textarea>
                    </div>
                    <div class="right-img">
                        <div id="gridMap"></div>
                    </div>
                </div>
                <div class="bottom gis-main-container">
                    <table class="grid-info" style="margin-top:10px;height:90%">
                        <tr><td>辖区网格数</td><td>{{ gridArea.gridCount }}</td><td>辖区面积</td><td>{{ gridArea.gridArea }}</td><td>负责人</td><td></td></tr>
                        <tr><td>党员数量</td><td></td><td>两新组织数量</td><td></td><td>网格户数</td><td>{{ gridArea.houseCount }}</td></tr>
                        <tr><td>网格员数</td><td>{{ gridArea.gridWorker + gridArea.leaderWorker}}</td><td>全职网格员</td><td>{{ gridArea.gridWorker }}</td><td>兼职网格员数</td><td>{{ gridArea.partTimeWorker }}</td></tr>
                        <!--<tr><td>办公地址</td><td colspan="5">无</td></tr>-->
                        <!--<tr><td>联系方式</td><td colspan="5">无</td></tr>-->
                    </table>
                </div>
            </div>
        </div>
      </div>
    </el-dialog>

    <!-- 重点关注人群统计与分布 -->
    <el-dialog
      ref="focusChartialog"
      append-to-body
      :visible.sync="focusChartWindowFlowBox"
      :fullscreen="false"
      custom-class="people_dialog"
      :class="minimizeClass"
      :modal="modalFlag"
    >
      <template slot="title">
        <div>
          <span><font>重点关注人群统计与分布</font></span>
          <!-- <div class="minimize-button" @click="miniWindow"><icon class="el-icon-cpu" /></div> -->
        </div>
      </template>
      <div class="people-list-window" id="gridInfoWindow">
        <div class="window">
            <div class="focus-title-panel">
                <div class="focus-title" @click="selectDept('focusGrid')">当前网格：{{ focusGridName }}></div>
            </div>
            <div class="focus-title-panel">
                <div :class="focusPeopleType ==='' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('','特殊人群总量')" >特殊人群总量</div>
                <div :class="focusPeopleType ==='correct_personnel' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('correct_personnel','社区矫正')" >社区矫正</div>
                <div :class="focusPeopleType ==='mental_patient' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('mental_patient','肇事肇祸')">肇事肇祸</div>
                <div :class="focusPeopleType ==='release_personnel' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('release_personnel','刑满释放')">刑满释放</div>
                <div :class="focusPeopleType ==='drug_addicts' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('drug_addicts','吸毒人员')">吸毒人员</div>
                <div :class="focusPeopleType ==='aids_patients' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('aids_patients','艾滋病人')">艾滋病人</div>
                <div :class="focusPeopleType ==='key_youth' ? 'type-button type-active':'type-button'" @click="focusTypeBtn('key_youth','重点青少年')">重点青少年</div>
            </div>
            <div class="focus-title-panel" style="padding-left: 20px;">
                总计 {{ focusTotalCount }}人
            </div>
            <div class="window-content" style="height: 280px;">
                <div class="left-chart" id="focusLeftChart" ref="focusLeftChart" style="width:49%;height:260px">

                </div>
                <div class="right-chart" style="width:49%;height:260px" v-bind:class="{ open : focusPeopleType === '' }">
                  <div id="focusRightChart" ref="focusRightChart" style="width:100%!important;height:100%!important;" ></div>
                </div>
                <div class="right-chart" style="width:49%;height:260px" v-bind:class="{ open : focusPeopleType !== '' }">
                    <div class="map-title">{{ focusPeopleTypeName }}人群分布</div>
                    <div class="sub-title">
                        <span>{{ focusMapGridName }}  {{ focusMapFocusCount }} </span>
                        <span>单位（人）</span>
                    </div>
                    <div class="focus-map" id="focusRightMap"></div>
                </div>
            </div>
        </div>
      </div>
    </el-dialog>

    <!-- 实有人口符合条件查询结果 -->
    <el-dialog
      ref="peopleListDialog"
      append-to-body
      :visible.sync="peopleListWindowFlowBox"
      :fullscreen="false"
      custom-class="people_dialog"
      :class="minimizeClass"
      :modal="modalFlag"
    >
      <template slot="title">
        <div>
          <span>实有人口符合条件查询结果-<font id="peopleTotalCount">{{peopleCount}}</font>条</span>
          <!-- <div class="minimize-button" @click="miniWindow"><icon class="el-icon-cpu" /></div> -->
        </div>
      </template>
      <div class="people-list-window" id="gridInfoWindow">
        <div class="window">
            <div class="window-content" id="listContent">
                <div class="table-container">
                    <el-table
                    :data="searchTableData"
                    border
                    style="width: 100%;height:500px;">
                    <el-table-column
                      prop="name"
                      label="姓名"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="sex"
                      label="性别"
                      sortable
                    >
                      <template slot-scope="scope">
                        {{scope.row.sex == "1" ? "男":(scope.row.sex == "2"?"女":'')}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="birthday"
                      label="出生日期">
                    </el-table-column>
                    <el-table-column
                      prop="mobile"
                      label="联系方式"
                      width="120"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="workerType"
                      label="人员类型"
                      width="100"
                    >
                      <template slot-scope="scope" >
                        <img v-for="(item,index) in typeOfKeyImgList(scope.row)" :key="index" :src="item" style="width:20px;height:20px" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="gridId"
                      label="GIS">
                      <template slot-scope="scope">
                        <icon class="el-icon-aim" @click="zoomTo(scope.row.id)" :style="scope.row.lat ? 'color:blue':''" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop=""
                      label="">
                      <template slot-scope="scope">
                        <el-link type="primary" @click="getPeopleDetail(scope.row.id)">人员详情</el-link>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop=""
                      label="">
                      <template slot-scope="scope">
                        <el-link type="primary" @click="openHouseDetail(scope.row.houseId)" >住房详情</el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="peopleCount"
                  :current-page.sync="peoplePage.currentPage"
                  :page-size="peoplePage.pageSize"
                  @current-change="handlePeopleCurrentChange"
                  style="text-align: center;">
                </el-pagination>
            </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      title="选择定位点"
      ref="mapZtreeDialog"
      append-to-body
      :visible.sync="mapZtreeFlowBox"
      :fullscreen="false"
      custom-class="ztree_dialog"
    >
      <gis-ztree style="height:100%;" v-on:getZtreeMap="getZtreeData($event)" />
    </el-dialog>

    <!-- 人员详情 -->
    <el-dialog
      title="人员详情"
      ref="peopleDetailDialog"
      append-to-body
      :visible.sync="peopleDetailFlowBox"
      :fullscreen="false"
      custom-class="detail_dialog"
    >
      <people-detail style="height:750px;overflow-y:auto;" :peopleId="peopleId" :key="componentKey" :dictArr="dictItemArr" />
    </el-dialog>

    <!-- 房屋详情 -->
    <el-dialog
      title="房屋详情"
      ref="houseDetailDialog"
      append-to-body
      :visible.sync="houseDetailFlowBox"
      :fullscreen="false"
      custom-class="detail_dialog"
    >
      <house-detail style="height:850px;overflow-y:auto;" :houseId="houseId" />
    </el-dialog>

    <!-- 楼栋详情 -->
    <el-dialog
      title="楼栋详情"
      ref="buildingDetailDialog"
      append-to-body
      :visible.sync="buildingDetailFlowBox"
      :fullscreen="false"
      custom-class="detail_dialog"
    >
      <build-detail style="height:850px;overflow:hidden;" :key="componentKey" :buildingId="buildingId" :buildingUnit="buildingUnit" :houseNumber="houseNumber" />
    </el-dialog>
  </div>
</template>
<script>
import {loadScript, loadCss,loadModules} from 'esri-loader';
import website from '@/config/website';
import $ from 'jquery';
import {getNextLevelGridServerNameByDeptCode,
        getAppendParamByDeptCode
        } from "@/assets/js/gis/util.js";
// import "@/assets/js/gis/extras/TDTLayer.js"
// import "@/assets/js/gis/extras/TDTAnnoLayer.js"
import "@/assets/css/gis/people.css";
import "@/assets/css/gis/coordinate.css";

import gisZtree from '@/components/gis/gisZtree'
import peopleDetail from '@/components/gis/peopleDetail'
import houseDetail from '@/components/gis/houseDetail'
import buildDetail from '@/components/gis/buildDetail'

import {populationTypeStructure, getGridBaseCount, codeList, getSpecialCount, workerList, getWorkerStructure, gridBrief,focusYearChange,focusCountByGridId,peopleList,getHouseAndBuildingInfo} from "@/api/xapply/doubleReal/peopleGis"

import {getLoginDept} from '@/api/system/dept'

// const GridId = 1123598813738675201;
// let DeptCode = "3701";
// let DeptName = "\u6D4E\u5357\u5E02";
let wkid=website.wkid
let pieChart, focusPieChart,focusLeftChart
let map,focusRightMap, graphicsLayer, peopleArray, workerArray,gridLayer,workerLayer,gridFillSymbol,gridMap,gridGraphicsLayer

// let workerTypeCode = {
//     "01": "网格员",
//     "02": "兼职网格员",
//     "03": "网格长"
// };
// const GridId = 100;

const echarts = require('echarts');

export default {
  name: 'people_gis',
  data() {
    return {
      show1:true,
      show2:true,
      show3:true,
      show4:true,
      show5:true,
      componentKey:1,
      workerTypeCode:{
        "01": "网格员",
        "02": "兼职网格员",
        "03": "网格长"
      },

      deptType:'',
      minimizeClass:'',
      modalFlag:true,
      mapZtreeFlowBox:false,
      gridWorkerFlowBox:false,
      gridWorkerInfoFlowBox:false,
      focusChartWindowFlowBox:false,
      peopleListWindowFlowBox:false,
      peopleDetailFlowBox:false,
      peopleId:'',
      houseDetailFlowBox:false,
      houseId:0,
      buildingDetailFlowBox:false,
      buildingId:0,
      buildingUnit:'',
      houseNumber:'',
      activeName: 'first',
      activeNames: ['1','2','3','4','5'],
      form:{},
      //默认为用户所在网格名称、网格ID、网格级别、网格编码。此四项变量随页面左上角的网格点选切换改变。
      //改变后影响网格信息内的网格数量、网格员数量、网格面积、特殊人群数量等统计数字。同时，这四类数据的点击弹窗的内容，
      //也根据左上角点选网格切换进行改变。
      distinct: '',
      gridId: '',
      gridLevel: 1,
      deptCode: '',

      //重点人群弹窗中，点击切换网格，统计重点人员信息。此两参数标识选中网格。
      focusGridId: '',
      focusGridName: '',
      focusPeopleType:"",
      focusPeopleTypeName: "",
      focusGridLevel: 1,
      focusGridDeptCode: '',
      focusTotalCount: 0,
      focusMapGridName:"",
      focusMapFocusCount:"",
      //点击网格员数量，弹出网格员信息列表。根据上访点选的网格进行统计。下方为查询条件参数。
      workerName: "",
      workerSex: "",
      workerPhone: "",
      workerType: "('01','02','03')",
      // workerType: "",
      orderBy: "",
      ascOrDesc: "",
      workerPageSize: 8,
      workerPageNum: 1,
      workerTitleText:"",
      workerCount: 0,

      //网格员列表
      tableData: [],

      //搜索结果列表
      searchTableData:[],

      //网格简介内容绑定
      gridArea: {
          gridName: "",
          gridBrief: "",
          gridCount: 0,
          gridArea: 0,
          houseCount: 0,
          gridWorker: 0,
          partTimeWorker: 0
      },
      //四个统计数字绑定。
      c1: '0',
      c2: '0',
      c3: '0',
      c4: '0',
      //人口检索条件内的数据绑定。
      areaText: "",
      ageFrom: "",
      ageTo: "",
      name: '',
      idCard: '',
      focusId:'',
      areaId: '',
      nationId: '',
      focusTypeId:'',
      populationTypeId: '',
      educationCode: '',
      religionId: '',
      partyId: '',
      gridMemberList: [],
      options: [
          {text: '济南市', value: '1'}
      ],
      focus: [
          {text: '全部', value: ''}
      ],
      nation: [
          {text: '全部', value: ''}
      ],
      sys_population_type: [
          {text: '全部', value: ''}
      ],
      education: [
          {text: '全部', value: ''}
      ],
      religion: [
          {text: '全部', value: ''}
      ],
      party: [
          {text: '全部', value: ''}
      ],
      types_of_key_personnel: [
          {text: '全部', value: ''}
      ],
      dictItemArr:{
        sex: [{value:'1',text:"男"},{value:'0',text:"女"}],
        nation:[],
        party:[],
        religion:[]
      },
      peopleDetail: {name:"",idCardNo:"",usedName:"",mobile:"",nation:"",sex:"",politics:"",education:"",religion:''},
      pageSize: 8,
      pageNum: 1,
      peopleCount: 0,
      peopleSearchStatue : 'button',

      peoplePage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },

      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },

      config: {
        cameraServerUrl: 'GIS_CAMERA',
        baseGridServerUrl: 'GIS_GRID',
        topDeptCode: '',
        topGridId: ''
      },
    };
  },
  components:{
    gisZtree,
    peopleDetail,
    houseDetail,
    buildDetail
  },
  mounted() {
    this.init();

    // // 数据查询初始化
    this.initData();
    console.log("mounted")
  },
  created() {
    console.log("created")
    // 数据查询初始化
    this.initData();

    let _this=this;
    window.getPeopleDetail = _this.getPeopleDetail;
  },
  methods: {
    changeFrom: function(e) {
      //限制长度
      this.ageFrom = (e > 0 && e <= 150) ? this.ageFrom.slice(0,150) : (e < 0 ? 0 : (e > 150 ? 150 :this.ageFrom.slice(0,150)))
    },

    changeTo: function(e) {
      //限制长度
      this.ageTo = (e > 0 && e <= 150) ? this.ageTo.slice(0,150) : (e < 0 ? 0 : (e > 150 ? 150 :this.ageTo.slice(0,150)))
    },


    //初始化地图
    init(){
      let _this = this;
      console.log("1")
      console.log("initurl:",website.InitUrl)
      loadScript({ url: website.InitUrl})
      loadCss(website.CssUrl)
      loadModules([
        "esri/map",
        "esri/layers/GraphicsLayer",
        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/dijit/HomeButton",
        "esri/geometry/Point",
        "esri/SpatialReference",
        'dijit/registry',
        "dojo/domReady!"
      ], { css: true }).then(([
        Map,
        GraphicsLayer,
        ArcGISTiledMapServiceLayer,
        HomeButton,
        Point,
        SpatialReference,
        registry
      ]) => {
        console.log("2")
        //实例化地图
        map = new Map("mapDiv", {
          center: website.MapCenterPoint,
          zoom: 12,
          slider: true, //缩放按钮移除
          logo: false, //logo移除
          isDoubleClickZoom: false,
          spatialReference:new SpatialReference(wkid)
        })

        let myTiledmapServiceLayer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl);
        map.addLayer(myTiledmapServiceLayer);

        graphicsLayer = new GraphicsLayer({id: "graphicsLayer"});
        map.addLayer(graphicsLayer);

        gridLayer = new GraphicsLayer({id: "gridLayer",visible: true});
        map.addLayer(gridLayer);

        workerLayer = new GraphicsLayer({id: "workerLayer"});
        map.addLayer(workerLayer);

        console.log("homebutton",registry.byId("homebutton"))

        if(registry.byId("homebutton")){
          registry.byId("homebutton").destroy()
        }

        let homeButton = new HomeButton({
          map: map,
          theme: "HomeButton",
          extent: null,
          visible: true
        }, "homebutton");

        homeButton.startup()

        map.on("load",mapLoad)

        function mapLoad(){
          let point = new Point(website.MapCenterPoint[0], website.MapCenterPoint[1], new SpatialReference(wkid));
          map.centerAndZoom(point,11);
          _this.getGridListByAttribute();
        }
      });
    },

    //选择定位点后的回调操作
    getZtreeData(data){
      console.log("treedata:",data)
      if(this.deptType === "distinct"){
        this.gridId = data.gridId;
        // this.deptCode = body.find('#deptCode').val();
        // this.gridLevel = body.find('#gridLevel').val();
        this.distinct = data.gridName.replace('-',' > ') + ' >>';

        this.refreshPieChart();
        this.refreshGridCount();
      }else if(this.deptType === "areaText"){
        this.areaText = data.gridName
        this.areaId = data.gridId
      }else{
        this.focusGridId = data.gridId
        this.focusGridName = data.gridName.replace('-',' > ') + ' >>';
      }

      this.mapZtreeFlowBox = false
    },

    refreshPieChart(){
      populationTypeStructure(this.gridId).then(result=>{
        this.initChart(result.data)
      })
    },

    refreshGridCount(){
      getGridBaseCount(this.gridId).then(result=>{
        this.c1 = result.data.houseCount + '个';
        this.c2 = result.data.memberCount + '个';
        this.c3 = result.data.houseArea + '㎡';
        this.c4 = result.data.gridCount + '个';
      })
    },

    /*双实人口左上角-选择网格*/
    selectDept(type) {
      this.mapZtreeFlowBox = true
      this.deptType = type
    },

    //tab标签单击事件
    handleClick(tab) {
      if(tab.name === 'first'){
          this.focusTypeId = '';
          this.isFocusOn = "";
      }else{
          // if(!focusPieChart){
          //   //获取特殊人群echarts饼图
          //   this.getFocusData();
          // }else{
          //   this.getFocusData();
          // }

          this.getFocusData();
          this.focusTypeId = '';
          this.isFocusOn = "Y";
      }
    },

    //获取特殊人群echarts饼图
    getFocusData(){
        getSpecialCount(this.gridId).then(result=>{
          //特殊人群echarts图表
          this.initFocusChart(result.data);
        })
    },

    //特殊人群echarts图表
    initFocusChart(data){
      // if(!focusPieChart){
      //   // focusPieChart = echarts.init(document.getElementById('focusPieChart'), 'infographic');
      //   focusPieChart = echarts.init(this.$refs.focusPieChart, 'infographic');
      // }
      focusPieChart = echarts.init(this.$refs.focusPieChart, 'infographic');

      let legendData = [];
      for (let i = 0; i < data.length; i++) {
          legendData.push(data[i].name);
      }

      let option = {
          title: {
              text: '特殊人群',
              subtext: '当年',
              x: 'center',
              show: false
          },
          tooltip: {
              trigger: 'item',
              position: 'top',
              formatter: "{a} <br/>{b} : {c} ({d}%)"
          },
          legend: {
              // orient: 'vertical',
              bottom: 10,
              left: 'center',
              data: legendData,
              show: true
          },
          toolbox: {
              show: false,
              feature: {
                  mark: {show: true},
                  dataView: {show: true, readOnly: false},
                  magicType: {
                      show: true,
                      type: ['pie', 'funnel'],
                      option: {
                          funnel: {
                              x: '25%',
                              width: '50%',
                              funnelAlign: 'bottom',
                              max: 1548
                          }
                      }
                  },
                  restore: {show: true},
                  saveAsImage: {show: true}
              }
          },
          calculable: true,
          series: [
              {
                  name: '人员类型',
                  type: 'pie',
                  radius: '40%',
                  center: ['50%', '36%'],
                  data: data,
                  label:{
                      normal:{
                          formatter: '{c}人'
                      }
                  },
                  itemStyle: {
                      normal: {
                          label: {
                              show: true
                          }, labelLine: {
                              show: true
                          }
                      }
                  }
              }
          ]
      };

      focusPieChart.setOption(option,true);
    },

    //人员详情弹窗
    getPeopleDetail(id) {
        // var options = {
        //     title: '人员详情',
        //     width: "1000",
        //     url:  "gis/peopleDetail/" + id
        // };
        // $.modal.openOptions(options);
      this.peopleId = id
      this.componentKey += 1
      this.peopleDetailFlowBox = true
    },

    initData() {
      //加载组织数据
      getLoginDept().then(res=>{
        this.deptCode = res.data.deptCode
        this.deptName = res.data.deptName
        this.focusGridName = res.data.deptName
        this.distinct = res.data.deptName
        this.gridId = res.data.id
        this.focusGridId = res.data.id
        this.gridLevel = res.data.gridLevel
        this.focusGridLevel = res.data.gridLevel
      })

      this.getGridCount();

      //echarts饼图
      populationTypeStructure().then(res=>{
        this.initChart(res.data);
      }).catch(error=>{
        console.log(error)
      })

      this.initCodeList('nation');
      this.initCodeList('sys_population_type');
      this.initCodeList('education');
      this.initCodeList('religion');
      this.initCodeList('party');
      this.initCodeList('types_of_key_personnel');
    },

    initChart(data) {
        if(!pieChart)
            pieChart = echarts.init(this.$refs.pieChart, 'infographic');
        let legendData = [];
        for (let i = 0; i < data.length; i++) {
            if(!data[i].name){
                data[i].name = "未知类型";
            }
            legendData.push(data[i].name);
        }

        let option = {
            title: {
                text: '人口结构',
                subtext: '当年',
                x: 'center',
                show: false
            },
            tooltip: {
                trigger: 'item',
                position: 'top',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
                // ,
                // position: 'right'
            },
            legend: {
                orient: 'vertical',
                x: '10%',
                y: 'center',
                data: legendData,
                show: true
            },
            toolbox: {
                show: false,
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {
                        show: true,
                        type: ['pie', 'funnel'],
                        option: {
                            funnel: {
                                x: '25%',
                                width: '50%',
                                funnelAlign: 'left',
                                max: 1548
                            }
                        }
                    },
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            series: [
                {
                    name: '人员类型',
                    type: 'pie',
                    radius: '55%',
                    center: ['65%', '50%'],
                    data: data,
                    label:{
                        normal:{
                            formatter: '{c}人'
                        }
                    },
                    itemStyle: {
                        normal: {
                            label: {
                                show: false
                            }, labelLine: {
                                show: false
                            }
                        }
                    }
                }
            ]
        };

        pieChart.setOption(option);
    },

    getGridCount() {
      getGridBaseCount().then(result=>{
        this.c1 = result.data.houseCount + '个';
        this.c2 = result.data.memberCount + '个';
        this.c3 = result.data.houseArea + '㎡';
        this.c4 = result.data.gridCount + '个';
      })

    },

    initCodeList(flag) {
      let _this = this
      codeList(flag).then(result=>{
        let cloneResult = JSON.parse(JSON.stringify(result.data));
        cloneResult.unshift({value: '', text: "无"});
        _this.dictItemArr[flag] = cloneResult;
        let text = "";
        switch (flag) {
          case "nation":
              text = "民族";
              break;
          case "sys_population_type":
              text = "居民类型";
              break;
          case "education":
              text = "学历";
              break;
          case "religion":
              text = "宗教类型";
              break;
          case "types_of_key_personnel":
              text = "特殊人员类型";
              break;
          case "party":
              text = "政治面貌";
              break;
        }
        result.data.unshift({value: '', text: text});
        _this[flag] = result.data;
      })
    },

    //网格
    initGrid() {
        if(!gridLayer.visible){
            gridLayer.setVisibility(true);
        }
        this.getGridListByAttribute();
    },

    //网格员
    initGridWorker() {
      this.gridWorkerFlowBox = true
      this.minimizeClass = ''

      this.getGridWorkerTitleInfo(this.gridId);
      this.searchWorker();
    },

    //网格简介
    initGridArea(){
        // $("#gridInfoWindow").show();
        this.gridWorkerInfoFlowBox = true

        gridBrief(this.gridId).then(result=>{
          if(!result.data.gridArea)
              result.data.gridArea = 0;
          if(!result.data.gridBrief)
              result.data.gridBrief = "";
          if(!result.data.gridWorker)
              result.data.gridWorker = 0;
          if(!result.data.partTimeWorker)
              result.data.partTimeWorker = 0;
          if(!result.data.leaderWorker)
              result.data.leaderWorker = 0;

          this.gridArea = result.data;
        }).catch(()=>{
          this.$message.error("查询网格信息出错")
        })

        console.log("gridarea",this.gridArea)

        if(!gridMap)
          this.initGridMap();
        else
          this.gridAreaMapSearch();
    },

    initGridMap(){
      loadModules([
        "esri/map",
        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/GraphicsLayer"
      ], { css: true })
      .then(([Map,ArcGISTiledMapServiceLayer,GraphicsLayer]) => {
        gridMap = new Map("gridMap", {center: website.MapCenterPoint, zoom: 12, logo: false, isDoubleClickZoom: false, slider:false});

        let myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl);
        gridMap.addLayer(myTiledMapServiceLayer);

        gridGraphicsLayer = new GraphicsLayer({id: "gridGraphicsLayer"});
        gridMap.addLayer(gridGraphicsLayer);

        gridMap.on("load",this.gridAreaMapSearch);
      })
    },

    gridAreaMapSearch() {
      loadModules([
        'esri/symbols/SimpleFillSymbol',
        "esri/symbols/SimpleLineSymbol",
        "esri/Color",
        "esri/geometry/Polygon",
        "esri/graphic",
        // "esri/symbols/Font",
        // "esri/symbols/TextSymbol",
        // "esri/geometry/Point",
        // "esri/SpatialReference",
        // "esri/graphicsUtils"
      ], { css: true })
      .then(([SimpleFillSymbol,SimpleLineSymbol, Color,Polygon,Graphic]) => {
        let _this = this
        let layer = _this.config.baseGridServerUrl;
        // if(parseInt(_this.gridLevel) < 5){
        //     layer += (parseInt(_this.gridLevel) + 1);
        // }else{
        //     layer += parseInt(_this.gridLevel);
        // }
        // let appendParam = "xzqhdm+LIKE+%27" + this.deptCode + "%25%27";

        layer += getNextLevelGridServerNameByDeptCode(_this.gridLevel)
        // let appendParam = "xzqhdm+LIKE+%27" + getAppendParamByDeptCode(_this.deptCode) + "%25%27";
        let appendParam = getAppendParamByDeptCode(_this.deptCode)

        let baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
        baseUrl += "&cql_filter=" + appendParam;
        console.log("空间查询开始时间：" + new Date());
        $.ajax({
            type: 'post',
            url: baseUrl,
            dataType: 'json',
            success: function (result) {
                console.log("空间查询结束时间：" + new Date());
                let featureSet = result.features;
                gridGraphicsLayer.clear();
                gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                    new Color([66, 0, 0]), 1), new Color([255, 99, 33, 0.15]));

                for (let i = 0; i < featureSet.length; i++) {
                    let obj = featureSet[i];
                    let polygonJson;
                    if (obj.geometry.type === "Polygon") {
                        polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": wkid}};
                    } else {
                        let geoArr = [];
                        for (let n = 0; n < obj.geometry.coordinates.length; n++) {
                            geoArr.push(obj.geometry.coordinates[n][0]);
                        }
                        polygonJson = {"rings": geoArr, "spatialReference": {"wkid": wkid}};
                    }
                    let polygon = new Polygon(polygonJson);
                    let gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                    gridGraphicsLayer.add(gra);

                    // var font = new esri.symbol.Font("13px", esri.symbol.Font.STYLE_NORMAL, esri.symbol.Font.VARIANT_NORMAL,
                    //     esri.symbol.Font.WEIGHT_NORMAL);
                    // var textSymbol = new esri.symbol.TextSymbol(
                    //     obj.properties.XZQHMC,
                    //     font, new esri.Color([0, 33, 99])
                    // );
                    // var labelPointGraphic = new esri.Graphic(new esri.geometry.Point(obj.properties.LNG, obj.properties.LAT, new esri.SpatialReference(4490)), textSymbol);
                    // gridGraphicsLayer.add(labelPointGraphic);
                }
                // gridMap.setExtent(GraphicsUtils.graphicsExtent(gridLayer.graphics));
            }
        });
      })
    },

    //重点关注人群统计与分布
    initGridSpecial(){
        // $("#focusChartWindow").fadeIn();
        this.focusChartWindowFlowBox = true

        this.initFocusLeftChart();
        this.initFocusRightChart();
    },

    //重点关注人群统计与分布 左侧 拆线ECHARTS
    initFocusLeftChart(){
        focusYearChange(this.focusGridId,this.focusPeopleType).then(result=>{
          console.log("focus_data:",result)
          let focus_data = result.data
          if(focus_data[focus_data.length - 1] && focus_data[focus_data.length - 1].count)
              this.focusTotalCount = focus_data[focus_data.length - 1].count;
          let yearArr = [];
          let countArr = [];
          for(let i=0;i<focus_data.length;i++){
              yearArr.push(focus_data[i].year);
              countArr.push(focus_data[i].count);
          }
          this.resetChart(yearArr,countArr);
        }).catch(error=>{
          this.$message.error("查询重点人员按照时间统计信息失败。错误：" + error)
          console.log("error:",error)
        })
    },

    //重点关注人群统计与分布 右侧 echarts
    initFocusRightChart(){
      getSpecialCount(this.gridId).then(result=>{
        let data = result.data

        let legendData = [];
        for (let i = 0; i < data.length; i++) {
            legendData.push({name:data[i].name,value:data[i].value});
        }

        let rightChart = echarts.init(this.$refs.focusRightChart,'infographic');
        let option = {
            title : {
                text: '特殊人群比例关系',
                textStyle: { color: '#222', fontFamily: "Microsoft YaHei",fontSize: 16},
                subtext: '单位%',
                x:'center',
                subtextStyle: { align: 'right'}
            },
            tooltip : {
                trigger: 'item',
                formatter: "{b} : <br/> {c} ({d}%)"
            },
            series : [
                {
                    name: '人员数量',
                    type: 'pie',
                    radius : '55%',
                    center: ['50%', '60%'],
                    labelLine: {show: false,length: 3,length2: 3},
                    data:legendData,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    // label: {
                    //     show:true,formatter:"{b}:{d}",color:'white',position: 'inside'
                    // }
                }
            ]
        };
        rightChart.setOption(option);
      })
    },

    //重点关注人群统计与分布 左侧 echarts重新渲染
    resetChart(yearArr,countArr){
      //if(!focusLeftChart){
        // focusPieChart = echarts.init(document.getElementById('focusPieChart'), 'infographic');
        focusLeftChart = null

        focusLeftChart = echarts.init(this.$refs.focusLeftChart);
      //}
      let leftFocusOption =  {
          title : {
              text: '特殊人群总量变化',
              textStyle: { color: '#222', fontFamily: "Microsoft YaHei",fontSize: 16},
              subtextStyle: { align: 'right'},
              subtext: '单位（人）',
              x:'center'
          },
          grid : {
              left: "20%",
              right: "5%",
              bottom: "15%"
          },
          xAxis: {
              type: 'category',
              splitLine: { show:true},
              nameGap: 30,
              boundaryGap: false,
              axisTick: {show:false},
              axisLine:{onZero: false,lineStyle:{color:'#ccc'}},
              data: yearArr
          },
          yAxis: {
              splitLine: { show:true},
              nameGap: 30,
              boundaryGap: false,
              axisTick: {show:false},
              axisLine:{onZero: false,lineStyle:{color:'#ccc'}},
              type: 'value'
          },
          series: [{
              data: countArr,
              type: 'line'
          }]
      };

      // if(focusLeftChart){
      //     leftFocusOption = focusLeftChart.getOption();
      //     console.log("leftFocusoption:",leftFocusOption)
      //     // leftFocusOption.xAxis.data = yearArr;
      //     // leftFocusOption.series[0].data = countArr;
      //     // focusLeftChart.clear();
      // }

      focusLeftChart.setOption(leftFocusOption,true);
    },

    //搜索获取网格员列表
    searchWorker() {
      var data = {
        gridId: this.gridId,
        workerName: this.workerName,
        workerSex: this.workerSex,
        workerPhone:this.workerPhone,
        workerType: this.workerType,
        orderBy: this.orderBy,
        ascOrDesc: this.ascOrDesc,
        size: this.page.pageSize,
        current:this.page.currentPage,
        page:this.page.currentPage
      };

      workerList(data).then(result=>{
        console.log("workerlist:",result.data)
        this.workerCount = result.data.data.total;
        workerArray = result.data.data.records;
        this.showWorkerList(workerArray);
      })
    },

    //页码点击事件
    handleCurrentChange(val){
      this.page.currentPage = val
      // this.workerCount = 0

      //重新获取数据
      this.searchWorker()
    },

    //搜索页码点击事件
    handlePeopleCurrentChange(val){
      this.peoplePage.currentPage = val
      // this.peopleCount = 0

      //重新获取数据
      this.searchPeople()
    },

    //显示网格员列表数据，并把网格员定位点打到地图上
    showWorkerList(arr){
        //赋值给表格
        this.tableData = arr

        //把网格员信息定位到GIS地图中
        this.addWorkerOnMap(arr);
    },

    //在地图上添加网格员定位点
    addWorkerOnMap(arr){
      loadModules([
        "esri/symbols/PictureMarkerSymbol",
        "esri/InfoTemplate",
        "esri/graphic",
        "esri/geometry/Point",
        "esri/SpatialReference",
      ], { css: true })
      .then(([PictureMarkerSymbol,InfoTemplate,Graphic,Point,SpatialReference]) => {
        map.infoWindow.resize(320,300);
        workerLayer.clear();

        let marker = new PictureMarkerSymbol("/img/member_1.png", 32, 32);
        for (let i = 0; i < arr.length; i++) {
            if (!arr[i].lng)
                continue;
            let obj = arr[i];
            let content = "<div class='map-window' style='width: 100%;'>\n" +
                "<div class='one-detail'>" +
                "<table style='border-bottom: 0px solid #FFF !important;'>" +
                "    <tr><td>姓名：</td><td>" + obj.name + "</td></tr>" +
                "    <tr><td>性别：</td><td>" + (obj.sex == "1" ? "男":(obj.sex == "2"?"女":'')) + "</td></tr>" +
                "    <tr><td>人员类型：</td><td>" + this.workerTypeCode[obj.workerType] + "</td></tr>" +
                "    <tr><td>联系方式：</td><td>" + this.killNull(obj.phoneNum) + "</td></tr>" +
                "    <tr><td>所属网格：</td><td>" + this.killNull(obj.gridName) + "</td></tr>" +
                "</table>" +
                "<div>";
            let infoTemplate = new InfoTemplate("网格员信息", content);
            let graphic = new Graphic(new Point(parseFloat(arr[i].lng), parseFloat(arr[i].lat), new SpatialReference(wkid)), marker, arr[i]);
            graphic.setInfoTemplate(infoTemplate);
            workerLayer.add(graphic);
        }
      })
    },

    getGridWorkerTitleInfo(gridid) {
      let _this = this

      getWorkerStructure(gridid).then(result=>{
        _this.workerTitleText = "共" + (result.data.fullTime + result.data.partTime) + "人 全职：" + result.data.fullTime + " 兼职：" + result.data.partTime;
      }).catch(error=>{
        console.log("查询网格员结构信息出错：" + error)
      })
    },

    getGridListByAttribute() {
      loadModules([
        'esri/symbols/SimpleFillSymbol',
        "esri/symbols/SimpleLineSymbol",
        "esri/Color",
        "esri/geometry/Polygon",
        "esri/graphic",
        "esri/symbols/Font",
        "esri/symbols/TextSymbol",
        "esri/geometry/Point",
        "esri/SpatialReference",
        // "esri/graphicsUtils"
      ], { css: true })
      .then(([SimpleFillSymbol,SimpleLineSymbol, Color,Polygon,Graphic,Font,TextSymbol,Point,SpatialReference]) => {
        let _this = this
        let layer = _this.config.baseGridServerUrl;
        // if(parseInt(_this.gridLevel) < 5){
        //     layer += (parseInt(getNextLevelGridServerNameByDeptCode(_this.gridLevel)) + 1);
        // }else{
        //     layer += parseInt(getNextLevelGridServerNameByDeptCode(_this.gridLevel));
        // }
        layer += getNextLevelGridServerNameByDeptCode(_this.gridLevel)
        // let appendParam = "xzqhdm+LIKE+%27" + getAppendParamByDeptCode(_this.deptCode) + "%25%27";
        let appendParam = getAppendParamByDeptCode(_this.deptCode)

        let baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
        console.log("baseUrl:",baseUrl)
        baseUrl += "&cql_filter=" + appendParam;
        // console.log("空间查询开始时间：" + new Date());
        $.ajax({
            type: 'post',
            url: baseUrl,
            dataType: 'json',
            success: function (result) {
                // console.log("空间查询结束时间：" + new Date());
                console.log("features:",result.features)
                let featureSet = result.features;
                gridLayer.clear();

                gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([66, 0, 0]), 1), new Color([255, 99, 33, 0.15]));

                if(result.features.length === 0){
                  // $.modal.alertWarning("此区域未划分网格。");
                }else{
                  for (let i = 0; i < featureSet.length; i++) {
                    let obj = featureSet[i];
                    let polygonJson;
                    if (obj.geometry.type === "Polygon") {
                        polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": wkid}};
                    } else {
                        let geoArr = [];
                        for (let n = 0; n < obj.geometry.coordinates.length; n++) {
                            geoArr.push(obj.geometry.coordinates[n][0]);
                        }
                        polygonJson = {"rings": geoArr, "spatialReference": {"wkid": wkid}};
                    }
                    let polygon = new Polygon(polygonJson);
                    let gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                    gridLayer.add(gra);

                    let font = new Font("13px", Font.STYLE_NORMAL, Font.VARIANT_NORMAL,Font.WEIGHT_BOLD);
                    let textSymbol = new TextSymbol(
                        obj.properties.xzqhmc,
                        font, new Color([0, 33, 99])
                    );
                    let labelPointGraphic = new Graphic(new Point(obj.properties.lng, obj.properties.lat, new SpatialReference(wkid)), textSymbol);
                    gridLayer.add(labelPointGraphic);
                }
                console.log("zoom:",map.getZoom())
                map.setZoom(14)

                // let polygonSingle = map.layerOp.getLayerSingle("gridLayer"); //获取图层信息
                // console.log("polygonsingle:",polygonSingle)

                // let geomePolygonSingle = polygonSingle.graphics[0].geometry; //获取图层中的几何信息
                // let extent = geomePolygonSingle.getExtent(); //获取图形范围信息
                // map.mapOp.setExtent(extent); //在地图上设置范围

                // map.setExtent(GraphicsUtils.graphicsExtent(gridLayer.graphics));
              }
            },
            error:function(error,status){
              console.log("error:",error)
              console.log("status:",status)
            }
        });
      })
    },

    killNull(obj){
        return obj ? obj : "";
    },

    truncateAddress(str) {
        return !str ? "" : str.length > 14 ? str.substr(0, 12) + '...' : str;
    },

    truncateWorkerName(str) {
        return !str ? "" : str.length > 7 ? str.substr(0, 6) + '...' : str;
    },

    //重点关注人群统计与分布 tab切换事件
    focusTypeBtn(type,name){
      // $(this).addClass("type-active").siblings().removeClass("type-active");
      this.focusPeopleType =  type;
      this.focusPeopleTypeName = name;
      this.initFocusLeftChart();

      if(this.focusPeopleType !== ""){
        setTimeout(this.initFocusRightMap(),1000);
      }
    },

    //重点关注人群统计与分布 加载右侧地图数据
    initFocusRightMap(){
      loadModules([
        "esri/map",
        "esri/layers/ArcGISTiledMapServiceLayer"
      ], { css: true })
      .then(([Map,ArcGISTiledMapServiceLayer]) => {
        let _this = this
        focusRightMap = new Map("focusRightMap", {center: website.MapCenterPoint, zoom: 10, logo: false, isDoubleClickZoom: false, slider: false});

        let myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl);
        focusRightMap.addLayer(myTiledMapServiceLayer);

        focusRightMap.on("load",_this.gridAreaFocusSearch());
        focusRightMap.on("click",function(e){
          console.log("mapclick:",e)
          console.log("attributes",e.graphic.attributes)
          console.log("grid_id:",e.graphic.attributes.grid_id)
          if(e.graphic && e.graphic.attributes && e.graphic.attributes.grid_id){
              _this.focusMapGridName = e.graphic.attributes.xzqhmc;
              _this.getFocusCountDataByGridId(e.graphic.attributes.grid_id);
          }
        });
      })
    },

    getFocusCountDataByGridId(gridId){
        focusCountByGridId({gridId: gridId,type: this.focusPeopleType}).then(result=>{
          this.focusMapFocusCount = result.num + "人";
        }).catch(error=>{
          this.$message.error("按照网格查询重点人员统计信息失败：" + error)
        })
    },

    //重点关注人群统计与分布 右侧地图数据加载
    gridAreaFocusSearch() {
      loadModules([
        'esri/symbols/SimpleFillSymbol',
        "esri/symbols/SimpleLineSymbol",
        "esri/Color",
        "esri/geometry/Polygon",
        "esri/graphic",
        "esri/symbols/Font",
        "esri/symbols/TextSymbol",
        "esri/geometry/Point",
        "esri/SpatialReference",
        // "esri/graphicsUtils",
        "esri/layers/GraphicsLayer"
      ], { css: true })
      .then(([SimpleFillSymbol,SimpleLineSymbol, Color,Polygon,Graphic,Font,TextSymbol,Point,SpatialReference,GraphicsLayer]) => {
        let _this = this
        let layer = _this.config.baseGridServerUrl;
        // if(parseInt(this.focusGridLevel) < 5){
        //     layer += (parseInt(this.focusGridLevel) + 1);
        // }else{
        //     layer += parseInt(this.focusGridLevel);
        // }
        // let appendParam = "xzqhdm+LIKE+%27" + this.focusGridDeptCode + "%25%27";

        layer += getNextLevelGridServerNameByDeptCode(_this.gridLevel)
        // let appendParam = "xzqhdm+LIKE+%27" + getAppendParamByDeptCode(_this.deptCode) + "%25%27";
        let appendParam = getAppendParamByDeptCode(_this.deptCode)

        let baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
        baseUrl += "&cql_filter=" + appendParam;
        console.log("空间查询开始时间：" + new Date());
        $.ajax({
            type: 'post',
            url: baseUrl,
            dataType: 'json',
            success: function (result) {
                console.log("空间查询结束时间：" + new Date());
                console.log("focusmap:",result)
                let featureSet = result.features;
                // focusRightMap.graphics.clear();

                console.log("focusRightGraphicsLayer:",focusRightMap)

                let focusRightGraphicsLayer = new GraphicsLayer({id: "focusRightGraphicsLayer"});
                focusRightMap.addLayer(focusRightGraphicsLayer);

                gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([66, 0, 0]), 1), new Color([255, 99, 33, 0.15]));
                console.log("start:")
                for (let i = 0; i < featureSet.length; i++) {
                    let obj = featureSet[i];
                    let polygonJson;
                    if (obj.geometry.type === "Polygon") {
                        polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": wkid}};
                    } else {
                        let geoArr = [];
                        for (let n = 0; n < obj.geometry.coordinates.length; n++) {
                            geoArr.push(obj.geometry.coordinates[n][0]);
                        }
                        polygonJson = {"rings": geoArr, "spatialReference": {"wkid": wkid}};
                    }
                    let polygon = new Polygon(polygonJson);
                    let gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                    focusRightGraphicsLayer.add(gra);

                    let font = new Font("13px",Font.STYLE_NORMAL, Font.VARIANT_NORMAL,Font.WEIGHT_NORMAL);
                    let textSymbol = new TextSymbol(
                        obj.properties.xzqhmc,
                        font,
                        new Color([0, 33, 99])
                    );
                    let labelPointGraphic = new Graphic(new Point(obj.properties.lng, obj.properties.lat, new SpatialReference(wkid)), textSymbol);
                    focusRightGraphicsLayer.add(labelPointGraphic);
                }
                console.log("end:")

                // focusRightMap.setExtent(GraphicsUtils.graphicsExtent(focusRightGraphicsLayer.graphics));
                focusRightMap.setZoom(12)
            }
        });
      })
    },

    zoomToWorker(id) {
      loadModules([
        "esri/geometry/Point",
        "esri/SpatialReference"
      ], { css: true })
      .then(([Point,SpatialReference]) => {
        for (let i = 0; i < workerArray.length; i++) {
            if (workerArray[i].id == id) {
                if(!workerArray[i] || !workerArray[i].lng){
                    this.$message.error('未采集位置信息。');
                }else{
                    map.centerAt(new Point(parseFloat(workerArray[i].lng), parseFloat(workerArray[i].lat), new SpatialReference(wkid)));
                }
                break;
            }
        }
      })
    },

    zoomTo(id) {
      loadModules([
        "esri/geometry/Point",
        "esri/SpatialReference"
      ], { css: true })
      .then(([Point,SpatialReference]) => {
        if(!id){
          if(!peopleArray[0] && !peopleArray[0].lng){
            this.$message.error('未采集位置信息。');
          }
          else{
            map.centerAt(new Point(parseFloat(peopleArray[0].lng), parseFloat(peopleArray[0].lat), new SpatialReference(wkid)));
          }
          return;
        }

        for (let i = 0; i < peopleArray.length; i++) {
          if (peopleArray[i].id == id) {
            if(!peopleArray[i] || !peopleArray[i].lng){
              this.$message.error('未采集位置信息。');
            }else{
              map.centerAt(new Point(parseFloat(peopleArray[i].lng), parseFloat(peopleArray[i].lat), new SpatialReference(wkid)));
            }
            break;
          }
        }
      })
    },

    closeSearch(){
      $('#workerSearchPanel').toggle();
    },

    miniWindow(){
      // $('#workerListWindow').toggleClass('minimize');

      this.minimizeClass = "minimize"
      this.modalFlag = false
    },

    resetForm() {
      // // this.$refs[formName].resetFields();
      // this.$nextTick(()=>{
      //   this.$refs[formName].resetFields();
      // })
      this.ageFrom = "";
      this.ageTo = "";
      this.name = "";
      this.idCard = "";
      this.areaId = "";
      this.nationId = "";
      this.populationTypeId = "";
      this.educationCode = "";
      this.religionId = "";
      this.partyId = "";
      this.areaText = "";
      this.focusTypeId="";
    },

    queryButton(){
      this.peopleListWindowFlowBox = true
      this.peopleSearchStatue = "button";
      this.page.currentPage = 1;
      this.searchPeople();
    },

    //搜索人员信息列表
    searchPeople() {
      if(workerLayer){
        workerLayer.clear();
      }

      let data = {
          gridId: this.areaId,
          name: this.name,
          idCard: this.idCard,
          nationCode: this.nationId,
          partyCode: this.partyId,
          religionCode: this.religionId,
          populationTypeCode: this.populationTypeId,
          educationCode: this.educationCode,
          ageFrom: this.ageFrom,
          ageTo: this.ageTo,
          focusTypeId:this.focusTypeId,
          isFocusOn:this.isFocusOn,
          size: this.peoplePage.pageSize,
          current: this.peoplePage.currentPage
      };

      peopleList(data).then(result=>{
        console.log("data",result)
        this.peopleCount = result.data.data.total;
        peopleArray = result.data.data.records;
        this.addToMap(peopleArray);

        //赋值给表格
        this.searchTableData = peopleArray
      })
    },

    //获取房屋信息
    openHouseDetail(houseId) {
      if(!houseId){
        $.modal.alertWarning("未采集房屋信息。");
      }else{
        console.log("houseId:",houseId)
        getHouseAndBuildingInfo(houseId).then(result=>{
          console.log("getHouseAndBuildingInfo:",result.data)
          if(result.data.success){
              if(result.data.houseType === "1"){
                  this.showBuildingDetailWindow(result.data.buildingId, result.data.buildingUnit, result.data.houseNumber);
              }else{
                  this.showHouseDetailWindow(result.data.houseId);
              }
          }else{
              this.$message.warning(result.data.errorMsg)
          }
        }).catch(error=>{
          this.$message.error("查询房屋信息出错。错误信息： " + error)
        })
      }
    },

    //房屋详情
    showHouseDetailWindow(id) {
      this.houseId = id
      // this.componentKey += 1;
      this.houseDetailFlowBox = true
    },

    //楼栋详情
    showBuildingDetailWindow(buildingId,buildingUnit,houseNumber) {
        this.buildingId = buildingId
        this.buildingUnit = buildingUnit
        this.houseNumber = houseNumber
        this.componentKey += 1;

        this.buildingDetailFlowBox = true
    },

    //把搜索到的人员信息定位到地图上
    addToMap(arr) {
      loadModules([
        "esri/symbols/PictureMarkerSymbol",
        "esri/InfoTemplate",
        "esri/graphic",
        "esri/geometry/Point",
        "esri/SpatialReference",
      ], { css: true })
      .then(([PictureMarkerSymbol,InfoTemplate,Graphic,Point,SpatialReference]) => {
        let _this = this

        map.infoWindow.resize(320,300);
        map.graphics.clear();

        console.log("arr:",arr)

        let marker = new PictureMarkerSymbol("/img/map-man.png", 32, 32);
        for (let i = 0; i < arr.length; i++) {
            if (!arr[i].lng)
                continue;
            let obj = arr[i];
            let typesOfKeyPersonnel = obj.typesOfKeyPersonnel;
            let typeOfKeyImgList = "";
            if(typesOfKeyPersonnel && typesOfKeyPersonnel.split(';').length > 0){
              let typesArr = typesOfKeyPersonnel.split(';');
              for(let j = 0;j<(typesArr.length > 4 ? 4 : typesArr.length);j++){
                typeOfKeyImgList += "<img width='20' height='20' src='/img/" + typesArr[j]  + ".png'>";
              }
            }

            let age = "";
            if(obj.birthday){
              age = new Date().getFullYear() - parseInt(obj.birthday.substr(0,4)) ;
            }

            let content = "<div class='map-window'>\n" +
                "<div class='one-detail'>" +
                "<table style='border-bottom: 0px solid #FFF !important;'>" +
                "    <tr><td>姓名：</td><td>${name}</td></tr>" +
                "   <tr><td>年龄：</td><td>" + age + "</td></tr>" +
                "    <tr><td>人员类型：</td><td>" + _this.populationTypeToText(arr[i].populationType) + "</td></tr>" +
                "    <tr><td>联系方式：</td><td>${mobile}</td></tr>" +
                "    <tr><td>常住地址：</td><td>${liveAddrDetail}</td></tr>" +
                "</table>" +
                "<div>";
            if(obj.photoLink)
                content += "<img style='margin: 0 5px 5px;height: 90px;' src=profile/population/" + obj.photoLink +">";
            else if(obj.sex === '1'){
                content += '<img style="margin: 0 5px 5px;height: 90px;" src="/img/man_default.jpg">';
            }else{
                content += '<img style="margin: 0 5px 5px;height: 90px;" src="/img/woman_default.png">';
            }

            let detailStr = '<div class="detail-button-container"><div class="detail-button" onclick="getPeopleDetail(\'' + obj.id + '\')">详情</div></div>';
            content += typeOfKeyImgList + detailStr + "</div></div></div>";

            let infoTemplate = new InfoTemplate("个人信息", content);
            let graphic = new Graphic(new Point(parseFloat(arr[i].lng), parseFloat(arr[i].lat), new SpatialReference(wkid)), marker, arr[i]);
            graphic.setInfoTemplate(infoTemplate);
            map.graphics.add(graphic);
        }
      })
    },

    //计算人员类型
    populationTypeToText () {
        let flag = "sys_population_type";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.populationType){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },
  },
  computed:{
    nationToText: function () {
        let flag = "nation";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.nation){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },

    sexToText: function () {
        let flag = "sex";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.sex){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },

    partyToText: function () {
        let flag = "party";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.politics){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },

    religionToText: function () {
        let flag = "religion";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.religion){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },

    educationToText: function () {
        let flag = "education";
        if(this.dictItemArr && this.dictItemArr[flag]){
            for(let i=0;i<this.dictItemArr[flag].length;i++){
                if(this.dictItemArr[flag][i].value === this.peopleDetail.education){
                    return this.dictItemArr[flag][i].text;
                }
            }
        }
        return "";
    },

    // typeOfKeyImgList(){
    //   return function(row){
    //     let typesOfKeyPersonnel = row.typesOfKeyPersonnel;
    //     let typeOfKeyImgLists = "";
    //     if(typesOfKeyPersonnel && typesOfKeyPersonnel.split(';').length > 0){
    //       var arr = typesOfKeyPersonnel.split(';');
    //       for(var j = 0;j<(arr.length > 4 ? 4 : arr.length);j++){
    //         typeOfKeyImgLists += "<img width='20' height='20' src='/img/" + arr[j]  + ".png'>";
    //       }
    //     }

    //     return typeOfKeyImgLists
    //   }
    // },

    typeOfKeyImgList(){
      return function(row){
        let typesOfKeyPersonnel = row.typesOfKeyPersonnel;
        let typeOfKeyImgLists = [];
        if(typesOfKeyPersonnel && typesOfKeyPersonnel.split(';').length > 0){
          var arr = typesOfKeyPersonnel.split(';');
          for(var j = 0;j<(arr.length > 4 ? 4 : arr.length);j++){
            // typeOfKeyImgLists += "<img width='20' height='20' src='/img/" + arr[j]  + ".png'>";
            typeOfKeyImgLists.push("/img/" +arr[j]+".png")
          }
        }

        return typeOfKeyImgLists
      }
    }
  },

  beforeDestroy() {
    // if (this.view) {
    //   this.view.container = null
    // }
    pieChart = null
    focusLeftChart = null
  },
}
</script>

<style lang="scss" scoped>
.el-table__header tr,
        .el-table__header th {
            padding: 0;
            height: 30px;
            line-height: 30px;
        }
        .el-table__body tr,
        .el-table__body td {
            padding: 0;
            height: 30px;
            line-height: 30px;
        }
</style>
